#pragma once
#include <iostream>
#include <string>


#include <ctime>
#include <cstdio>

#include <unistd.h>
#include <stdarg.h>

//日志
//输出格式：日志等级+时间+进程PID+内容+errno+strerror
//logMessage(SAFE,"%s %d is safe","线程",16)


enum 
{
    Debug = 0, //测试
    Info, //普通信息
    Warning, //警告
    Error, //异常 - 退出
    Fatal, //危险 - 退出
    Uknown //未知异常 - 退出
};

static std::string toLevelString(int level) //日志等级获取
{
    switch (level)
    {
    case Debug:
        return "Debug";
    case Info:
        return "Info";
    case Warning:
        return "Warning";
    case Error:
        return "Error";
    case Fatal:
        return "Fatal";
    default:
        return "Uknown";
    }
}

static std::string getTime() //获取时间字符串 yyyy/mm/dd-HH:MM:SS
{
    time_t t = time(nullptr);
    struct tm* tmp = localtime(&t);
    char buf[1024] = {0};
    snprintf(buf,sizeof(buf),":%d/%d/%d-%d:%d:%d",tmp->tm_year+1900,tmp->tm_mon+1,tmp->tm_mday,tmp->tm_hour,tmp->tm_min,tmp->tm_sec);
    return buf;
}

//输出格式：日志等级+时间+进程PID+内容+errno+strerror
//分为两部分 日志等级+时间+进程PID 和 内容+errno+strerror
void logMessage(int level,const char* format,...)
{
    char leftbuf[1024] = {0};
    std::string Lel = toLevelString(level); //获取日志的等级字符串
    std::string t = getTime(); //获取时间
    snprintf(leftbuf,sizeof(leftbuf),"[Log Level:%s|Time:%s|Process PID:%d] Log Content: ",Lel.c_str(),t.c_str(),getpid());

    char rightbuf[1024] = {0};
    va_list p;
    va_start(p,format); //p指向可变参数列表的首参数位置
    vsnprintf(rightbuf,sizeof(rightbuf),format,p); //从第一个可变参数开始 一一提取参数写入rightbuf
    va_end(p); //p=NULL

    std::string s = leftbuf;
    s += rightbuf;

    //写入日志文件中
    //std::cout<<s<<std::endl; debug

    // FILE* fp = fopen("/home/ARMCSKGT/C++文件夹/Linux套接字编程/序列化/LOG/log.t","aw");
    // if(fp)
    // {
    //     fprintf(fp,"%s%s\n",leftbuf,rightbuf);
    //     fflush(fp);
    //     fclose(fp);
    // }
    // else std::cout<<"wirte log open file error!"<<std::endl;
    printf("%s%s\n",leftbuf,rightbuf);
}